
import java.awt.Rectangle;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import sun.applet.Main;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jVideos.java
 *
 * Created on Jun 15, 2010, 4:21:25 PM
 */

/**
 *
 * @author david
 */
public class jVideos extends javax.swing.JFrame {

    /** Creates new form jVideos */
    public jVideos() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        path = new javax.swing.JLabel();
        cutButton = new javax.swing.JToggleButton();
        vidPath = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        vidFolderSelect = new javax.swing.JTextField();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSlider1 = new javax.swing.JSlider();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        progressBar = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("jVideos::Mocha videos");
        setForeground(java.awt.Color.white);
        setModalExclusionType(java.awt.Dialog.ModalExclusionType.APPLICATION_EXCLUDE);

        jButton1.setText("Seleccionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel1.setText("Selecciona un video para cortarlo:");

        path.setText(" ");

        cutButton.setText("Cortar");
        cutButton.setEnabled(false);
        cutButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cutButtonActionPerformed(evt);
            }
        });

        vidPath.setEnabled(false);
        vidPath.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vidPathActionPerformed(evt);
            }
        });

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel2.setText("Selecciona una carpeta destino:");
        jLabel2.setEnabled(false);

        vidFolderSelect.setEnabled(false);
        vidFolderSelect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                vidFolderSelectActionPerformed(evt);
            }
        });

        jButton3.setText("Seleccionar");
        jButton3.setEnabled(false);
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel3.setText("Duración en segundos de cada corte:");
        jLabel3.setEnabled(false);

        jSlider1.setEnabled(false);
        jSlider1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jSlider1StateChanged(evt);
            }
        });

        jLabel4.setText(" ");

        jLabel5.setFont(new java.awt.Font("DejaVu Sans", 1, 12));
        jLabel5.setForeground(new java.awt.Color(1, 1, 1));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(20, 20, 20)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(jLabel1)
                                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                                .add(path))
                            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                                .add(vidPath, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
                                .add(1, 1, 1)
                                .add(jButton1))))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel2))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(vidFolderSelect, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 270, Short.MAX_VALUE)
                        .add(1, 1, 1)
                        .add(jButton3))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addContainerGap(243, Short.MAX_VALUE)
                        .add(cutButton)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jButton2))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jSlider1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(org.jdesktop.layout.GroupLayout.LEADING, jLabel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jLabel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 106, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .addContainerGap()
                        .add(jLabel5))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .addContainerGap()
                        .add(progressBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 357, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(path)
                    .add(jLabel1))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(vidPath, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton1))
                .add(18, 18, 18)
                .add(jLabel2)
                .add(6, 6, 6)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(vidFolderSelect, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jButton3))
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jSlider1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(jLabel5)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 16, Short.MAX_VALUE)
                .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(18, 18, 18)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jButton2)
                    .add(cutButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void loadVidPath(){
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Escoge un directorio con archivos de video");
        //chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int choice = chooser.showOpenDialog(this);
		if(choice == JFileChooser.CANCEL_OPTION) {

		}
		else {
			localFilePath = chooser.getSelectedFile().getAbsolutePath();
            vidPath.setText(localFilePath);
            //vidFolderSelect.setEnabled(true);
            jLabel2.setEnabled(true);
            jButton3.setEnabled(true);
            jLabel3.setEnabled(true);
            jSlider1.setEnabled(true);
           // jSlider1.setValue();
            jSlider1.setMinimum(1);
            duracion=obtenerInfoVideo(localFilePath);
            jSlider1.setMaximum(duracion); //***VALOR CABLEADO***//
            jSlider1.setValue(jSlider1.getMaximum()/2);
            jLabel4.setText(jSlider1.getValue()+" secs.");
            //cutButton.setEnabled(true);

        }
    }

    private void selectVidSaveFolderPath(){
        JFileChooser chooser = new JFileChooser();
        chooser.setCurrentDirectory(new java.io.File("."));
        chooser.setDialogTitle("Escoge un directorio para guardar los videos");
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int choice = chooser.showOpenDialog(this);
		if(choice == JFileChooser.CANCEL_OPTION) {

		}
		else {
			localFolderPath = chooser.getSelectedFile().getAbsolutePath()+"/";
            vidFolderSelect.setText(localFolderPath);
            cutButton.setEnabled(true);
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        loadVidPath();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cutButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cutButtonActionPerformed
         jLabel5.setText("Convirtiendo.");
         separarVideo(localFilePath, localFolderPath, duracion, jSlider1.getValue());
         jLabel5.setText("Operacion Finalizada.");
         cutButton.setEnabled(true);
    }//GEN-LAST:event_cutButtonActionPerformed

    private void vidPathActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vidPathActionPerformed
        loadVidPath();
    }//GEN-LAST:event_vidPathActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void vidFolderSelectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_vidFolderSelectActionPerformed
        selectVidSaveFolderPath();
    }//GEN-LAST:event_vidFolderSelectActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        selectVidSaveFolderPath();
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jSlider1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jSlider1StateChanged
        jLabel4.setText(jSlider1.getValue()+" secs.");
        secsCut = jSlider1.getValue();
    }//GEN-LAST:event_jSlider1StateChanged


    public void separarVideo(String video,String destino,int duracion, int separacion) {

        int corteActual = 0;
        int parte=0;
        String partVideoAddr[]=video.split("/");
        //System.out.print(partVideoAddr[(partVideoAddr.length)-1]);
        String name=partVideoAddr[(partVideoAddr.length)-1];
        System.out.print(name);

        //Inicializo componentes del XML




        //System.out.println(partVideoName[0]);
        progressBar.setEnabled(true);
        progressBar.setMinimum(1);
        progressBar.setMaximum(duracion);
        progressBar.setStringPainted(true);
        progressBar.setValue(parte);

        

        //progressBar.set
        //Generar archivos de imagen.
        try {
            int exitValue = -1;
            Runtime rt = Runtime.getRuntime();
            //System.out.print("llamare instruccion "+"ffmpeg -i " + video+" -target ntsc-dvd -ss "+corteActual+" "+destino+name+"_parte_"+parte+".mpg");
            //Process p = rt.exec("/usr/bin/ffmpeg -i /home/yessi/Escritorio/Redes3/videoplayback.flv -ar 22050 /home/yessi/Escritorio/video_salida.avi");
            //Process p = Runtime.getRuntime().exec("ffmpeg -i /home/fernando/Desktop/videoplayback.flv -target ntsc-dvd /home/fernando/Desktop/nando5.mpg");
            float uno =(float)1;
            float separ=(float)separacion;
            Process p = Runtime.getRuntime().exec("ffmpeg -i " + video+" -r 1 -f image2 -s 160x120 "+destino+name+"_imagen_%d.png");

            exitValue = esperar(p);

        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

        }


        while(corteActual<duracion) {

            try {
                int exitValue = -1;
                Runtime rt = Runtime.getRuntime();
                //System.out.print("llamare instruccion "+"ffmpeg -i " + video+" -target ntsc-dvd -ss "+corteActual+" "+destino+name+"_parte_"+parte+".mpg");
                //Process p = rt.exec("/usr/bin/ffmpeg -i /home/yessi/Escritorio/Redes3/videoplayback.flv -ar 22050 /home/yessi/Escritorio/video_salida.avi");
                //Process p = Runtime.getRuntime().exec("ffmpeg -i /home/fernando/Desktop/videoplayback.flv -target ntsc-dvd /home/fernando/Desktop/nando5.mpg");

                Process p = Runtime.getRuntime().exec("ffmpeg -i " + video+" -target ntsc-dvd -ss "+corteActual+" "+destino+name+"_parte_"+parte+".mpg");

                exitValue = esperar(p);

            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);

            }
            
        corteActual = corteActual + separacion;

        parte++;
        //System.out.println("parte es "+parte+"el num total es "+(duracion/separacion));
        progressBar.setValue(corteActual);
        Rectangle progressRect = progressBar.getBounds();
        progressRect.x = 0;
        progressRect.y = 0;
        progressBar.paintImmediately( progressRect );
        //System.out.println(progressBar.getValue());
        }



    };

    public static int obtenerInfoVideo (String video) {
        try {
            int exitValue = -1;
            Runtime rt = Runtime.getRuntime();
            //Process p = rt.exec("/usr/bin/ffmpeg -i /home/yessi/Escritorio/Redes3/videoplayback.flv -ar 22050 /home/yessi/Escritorio/video_salida.avi");
            //Process p = Runtime.getRuntime().exec("ffmpeg -i /home/fernando/Desktop/videoplayback.flv -target ntsc-dvd /home/fernando/Desktop/nando5.mpg");
            Process p = Runtime.getRuntime().exec("ffmpeg -i " + video);
            exitValue = esperarInfoProc(p);
            return exitValue;
        } catch (IOException ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            return -1;
        }

    }

    private static int esperar(Process p) {
    int exitValue = -1; // returned to caller when p is finished
    try {
        InputStream in = p.getInputStream();
        InputStream err = p.getErrorStream();
        String leido="";

        boolean finished = false; // Set to true when p is finished
        while (!finished) {
        try {
            while (in.available() > 0) {
              // Print the output of our system call
              Character c = new Character((char) in.read());
              //String c1=c.toString();
              //leido.concat(c1);
              System.out.print(c);
            }
            //System.out.print("tinqui");
           // System.out.print(leido);

            while (err.available() > 0) {
              // Print the output of our system call
              Character c = new Character((char) err.read());
              //String c1=c.toString();
              //leido=leido.concat(c1);
              System.out.print(c);
            }

        // Ask the process for its exitValue. If the process
        // is not finished, an IllegalThreadStateException
        // is thrown. If it is finished, we fall through and
        // the variable finished is set to true.
            exitValue = p.exitValue();
            finished = true;
        } catch (IllegalThreadStateException e) {
        // Process is not finished yet;
        // Sleep a little to save on CPU cycles
                                                                                            Thread.currentThread().sleep(500);
        }

        }


    } catch (Exception e) {
        // unexpected exception! print it out for debugging...
        System.err.println("doWaitFor(): unexpected exception - "
                                    + e.getMessage());
    }
    // return completion status to caller
    return 0;
    }


    private static int esperarInfoProc(Process p) {
        int exitValue = -1; // returned to caller when p is finished
        try {
        InputStream in = p.getInputStream();
        InputStream err = p.getErrorStream();
        String leido="";

        boolean finished = false; // Set to true when p is finished
        while (!finished) {
        try {
            while (in.available() > 0) {
              // Print the output of our system call
              Character c = new Character((char) in.read());
              String c1=c.toString();
              leido.concat(c1);
              //System.out.print(c);
            }
            //System.out.print("tinqui");
           // System.out.print(leido);

            while (err.available() > 0) {
              // Print the output of our system call
              Character c = new Character((char) err.read());
              String c1=c.toString();
              leido=leido.concat(c1);
              //System.out.print(c);
            }

        // Ask the process for its exitValue. If the process
        // is not finished, an IllegalThreadStateException
        // is thrown. If it is finished, we fall through and
        // the variable finished is set to true.
            exitValue = p.exitValue();
            finished = true;
             //System.out.println(leido);
           //  Scanner scan = new Scanner(leido);
             int pos=leido.indexOf("Duration:");
             leido=leido.substring(pos+10,pos+21);;

        //    leido=leido.substring(10,21);
            String[] dur=leido.split(":");
           // System.out.print(dur[0]+"  "+dur[1]+" "+dur[2]);
            Integer horas = Integer.parseInt(dur[0]);
            Integer minutos = Integer.parseInt(dur[1]);
            float segundos = Float.valueOf(dur[2]).floatValue();
            segundos = segundos + (60*minutos.intValue()) + (3600*horas.intValue());
            exitValue = Float.valueOf(segundos).intValue()+1;
           // System.out.println(segundos+" "+exitValue);

       //     System.out.print(leido);
          //    System.out.print(scan.next());
        //while(!scan.hasNext("Duration:")) {
          //  scan.next();
        //}
        //int horas = scan.nextInt();
      //  int minutos = scan.nextInt();
       // float segundos = scan.nextFloat();
     //   segundos = segundos + horas*3600 + minutos*60;
   //     System.out.println("\n\nlos segundos son: "+segundos);
      //  } else System.out.println("No encontre nada =(");
        } catch (IllegalThreadStateException e) {
        // Process is not finished yet;
        // Sleep a little to save on CPU cycles
                                                                                            Thread.currentThread().sleep(500);
        }
        }




        } catch (Exception e) {
        // unexpected exception! print it out for debugging...
        System.err.println("doWaitFor(): unexpected exception - "
                                    + e.getMessage());
        }
        // return completion status to caller
        return exitValue;
        }


    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jVideos().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton cutButton;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSlider jSlider1;
    private javax.swing.JLabel path;
    private javax.swing.JProgressBar progressBar;
    private javax.swing.JTextField vidFolderSelect;
    private javax.swing.JTextField vidPath;
    // End of variables declaration//GEN-END:variables
    public static String localFilePath;
    public static String localFolderPath;
    public static int duracion;
    int secsCut;
}
